package com.leetcode.LeetCode精选TOP面试题;

/**
 * @author 覃国强
 * @date 2022-06-16 16:14
 */
public class 题库_0116_填充每个节点的下一个右侧节点指针 {

  static
  class Solution {
    public Node connect(Node root) {
      if (root == null || root.right == null) {
        return root;
      }

      Node leftmostFather = root;
      Node node = leftmostFather.left;
      while (node != null) {
        Node father = leftmostFather;
        while (father != null) {
          if (father.left == node) {
            node.next = father.right;
          } else {
            father = father.next;
            node.next = father != null ? father.left : null;
          }
          node = node.next;
        }
        leftmostFather = leftmostFather.left;
        node = leftmostFather.left;
      }

      return root;
    }
  }


  class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
      val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
      val = _val;
      left = _left;
      right = _right;
      next = _next;
    }
  };
}
